/*
 * $Id: AbstractHttpMessageContextImpl.java 41065 2007-01-18 23:08:28Z jdamick $
 *
 * Copyright 2006- Revolution Health Group.  All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of Revolution Health Group.  (Confidential Information).
 * You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license 
 * agreement you entered into with Revolution Health Group.
 *
 */
package org.javason.http;

import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.javason.util.Debug;

public class AbstractHttpMessageContextImpl implements HttpMessageContext {
	private static final Logger _log = Logger.getLogger(AbstractHttpMessageContextImpl.class);
	private HttpServletRequest _request;
	private String _serviceName;

	public AbstractHttpMessageContextImpl(String serviceName, HttpServletRequest request) {
		_serviceName = serviceName;
		_request = request;
	}
	
	public Cookie[] getCookies() {
		return _request.getCookies();
	}

	@SuppressWarnings("unchecked")
	public Map<String, String[]> getParameters() {
		return (Map<String, String[]>)_request.getParameterMap();
	}

	public HttpServletRequest getHttpServletRequest() {
		return _request;
	}


	public String getServiceName() {
		return _serviceName;
	}
	
	public void setServiceName(String serviceName) {
		_serviceName = serviceName;
	}
	
	public Cookie getCookie(String cookieName) {
		Cookie result = null;
		if (getCookies() != null) {
			for (Cookie cookie : getCookies()) {
				if (cookie.getName().equals(cookieName)) {
					result = cookie;
					break;
				}
			}
		}
		
		return result;
	}
	
	public Cookie getSessionCookie() {
		return getCookie("_session_id");
	}
	
	public Cookie getClearTrustCookie() {
		return getCookie("CTSESSION");
	} 
	
	public String getClearTrustToken() {
		Cookie ct = getClearTrustCookie();
		String result = "";
		if (ct != null) {
			result = ct.getValue();
		}
		return result;
	}
	
	public static String getSessionId(Cookie sessionCookie) {
		String sessionId = "-1";
		if (sessionCookie != null) {
			sessionId = sessionCookie.getValue();
			Debug.log(_log, "Session ID[%s]", sessionId);
		} else {
			Debug.log(_log, "Session ID NOT FOUND");
		}
		return sessionId;
	}
	
	public String getSessionId() {
		return getSessionId(getSessionCookie());
	}
	
	public void debugCookies() {
		if (_log.isDebugEnabled()) {
			if (getCookies() != null) {
				Debug.log(_log, "Cookies length: %s", getCookies().length);
				for (Cookie cookie : getCookies()) {
					Debug.log(_log, "Cookie[%s] = %s", cookie.getName(), cookie.getValue());
					Debug.log(_log, "Cookie = %s", cookie);
				}
			} else {
				Debug.log(_log, "Cookies are NULL");
			}
		}
	}
}
